package besta

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/net"
)

// Generate 生成机器码
func Generate() string {
	cpuInfos, err := cpu.Info()
	if err != nil {
		fmt.Println("get system info fail:100")
		return ""
	}

	netInfos, err := net.Interfaces()
	if err != nil {
		fmt.Println("get system info fail:101")
		return ""
	}

	code := []byte(cpuInfos[0].PhysicalID + netInfos[0].HardwareAddr)

	// AES加密
	encrypted := aesEncryptCBC(code, gKey)
	// 编码到字符串
	s := hex.EncodeToString(encrypted)
	// 后12位作为机器码打印
	return s[len(s)-12:]
}

func aesEncryptCBC(origData []byte, key []byte) (encrypted []byte) {
	// 分组秘钥
	// NewCipher该函数限制了输入k的长度必须为16, 24或者32
	block, _ := aes.NewCipher(key)
	blockSize := block.BlockSize()                              // 获取秘钥块的长度
	origData = pkcs5Padding(origData, blockSize)                // 补全码
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) // 加密模式
	encrypted = make([]byte, len(origData))                     // 创建数组
	blockMode.CryptBlocks(encrypted, origData)                  // 加密
	return encrypted
}

func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}
